package com.tengol.course.spring.boot.boot01.listener;

import com.alibaba.fastjson.JSON;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;

/**
 * Spring 应用程序运行监听器，可以监听每个运行阶段，针对每个阶段进行特别的设置
 *
 * @author dongrui
 * @date 2020/05/16
 */
public class HelloSpringApplicationRunListener implements SpringApplicationRunListener {

    /**
     * 必须要有的构造方法，没有时会报错：java.lang.NoSuchMethodException
     */
    public HelloSpringApplicationRunListener(SpringApplication springApplication, String[] args){
        System.out.println("==== HelloSpringApplicationRunListener 的构造方法  ...");
    }

    @Override
    public void starting() {
        System.out.println("==== HelloSpringApplicationRunListener.starting() ...");
    }

    @Override
    public void environmentPrepared(ConfigurableEnvironment environment) {
        System.out.println("==== HelloSpringApplicationRunListener.environmentPrepared() ...");
        String property = environment.getProperty("os.name");
        System.out.println("==== os.name = " + property);
    }

    @Override
    public void contextPrepared(ConfigurableApplicationContext context) {
        System.out.println("==== HelloSpringApplicationRunListener.contextPrepared() ...");
        String[] beanDefinitionNames = context.getBeanDefinitionNames();
        System.out.println("==== 当前容器包含的组件数：" + beanDefinitionNames.length);
    }

    @Override
    public void contextLoaded(ConfigurableApplicationContext context) {
        System.out.println("==== HelloSpringApplicationRunListener.contextLoaded() ...");
        String[] beanDefinitionNames = context.getBeanDefinitionNames();
        System.out.println("==== 当前容器包含的组件数：" + beanDefinitionNames.length);
    }

    @Override
    public void started(ConfigurableApplicationContext context) {
        System.out.println("==== HelloSpringApplicationRunListener.started() ...");
        String[] beanDefinitionNames = context.getBeanDefinitionNames();
        System.out.println("==== 当前容器包含的组件数：" + beanDefinitionNames.length);
    }

    @Override
    public void running(ConfigurableApplicationContext context) {
        System.out.println("==== HelloSpringApplicationRunListener.running() ...");
        String[] beanDefinitionNames = context.getBeanDefinitionNames();
        System.out.println("==== 当前容器包含的组件数：" + beanDefinitionNames.length);
    }

    @Override
    public void failed(ConfigurableApplicationContext context, Throwable exception) {
        System.out.println("==== HelloSpringApplicationRunListener.failed() ...");
        String[] beanDefinitionNames = context.getBeanDefinitionNames();
        System.out.println("==== 当前容器包含的组件数：" + beanDefinitionNames.length);
    }
}
